package com.tj.template.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Author: binary
 * Date: 2020/8/6 下午5:43
 */
@EnableAsync
@Configuration
public class TaskPoolConfig implements AsyncConfigurer {

    private final Logger LOGGER = LoggerFactory.getLogger(TaskPoolConfig.class);


    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        LOGGER.info("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3); //核心线程数
        executor.setMaxPoolSize(30);  //最大线程数
        executor.setQueueCapacity(100); //队列大小
        executor.setKeepAliveSeconds(60); //线程最大空闲时间
        executor.setThreadNamePrefix("taskExecutor-"); ////指定用于新创建的线程名称的前缀。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}
